<?php
declare (strict_types=1);

namespace app\api\controller\v2;

use app\common\model\Banner;
use app\common\model\Cate;
use app\common\model\Example as ExampleModel;
use app\common\model\ExampleCol;
use app\common\model\ExampleZan;
use think\facade\Db;

class Example extends BaseController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        //
        return sucessMsg('200', '获取成功', [
            'banner' => $this->banner(),//获取banner
            'cate' => $this->cate(),//获取分类cate
        ]);
    }

    /**
     * 获取实例banner
     */
    public function banner()
    {
        return Banner::where('type', 1)
            ->field('id,title,english')
            ->order('sort', 'asc')
            ->find();
    }

    /**
     * 获取大分类
     */
    public function cate()
    {
        return Cate::where(['type' => 1, 'status' => 1, 'pid' => 0])
            ->field('id,name,image')
            ->order('sort', 'asc')
            ->withAttr('image', function ($val, $data) {
                return env('app.yuming') . $val;
            })
            ->select();
    }

    /**
     * 获取小分类
     */
    public function cates()
    {
        $id = input('id/d');
        $cates = Cate::where(['type' => 1, 'status' => 1, 'pid' => $id])
            ->field('id,name')
            ->order('sort', 'asc')
            ->select();
        $cate = Cate::where(['type' => 1, 'status' => 1, 'id' => $id])
            ->field('id,name,image')
            ->order('sort', 'asc')
            ->withAttr('image', function ($val, $data) {
                return env('app.yuming') . $val;
            })
            ->select();
        return sucessMsg('200', '获取成功', ['cate' => $cate, 'cates' => $cates]);
    }

    /**
     * 获取实例列表
     */
    public function list()
    {
        $page = input('page/d', 1);
        $id = input('id/d');
        $model = new ExampleModel();
        $listRows = 8;
        $where['status'] = 1;
        if (empty($id)) {
            $list = $model->where($where)
                ->page($page, $listRows)
                ->field('id,title,image,param,zan_num,col_num')
                ->withAttr('image', function ($val, $data) {
                    return env('app.yuming') . $val;
                })
                ->withAttr('param', function ($val1, $data) {
                    return json_decode($val1);
                })
                ->select();
            $count = $model->where($where)->count();
            $maxpage = ceil($count / $listRows);
            return sucessMsg('200', '获取成功', ['list' => $list, 'page' => $page, 'maxpage' => $maxpage]);
        } else {
            $cates = Cate::where(['status' => 1, 'id' => $id])->find();
            if ($cates['pid'] == 0) {
                $cate = Cate::where(['status' => 1, 'pid' => $id])
                    ->field('id')
                    ->select()->toArray();
                if (empty($cate)) {
                    $where['cate_id'] = $id;
                } else {
                    $cate_id = array_column($cate, 'id');
                    $where = [
                        ['cate_id', 'in', $cate_id]
                    ];
                }
            } else {
                $where['cate_id'] = $id;
            }
            $list = $model->where($where)
                ->page($page, $listRows)
                ->field('id,title,image,param,zan_num,col_num')
                ->withAttr('image', function ($val, $data) {
                    return env('app.yuming') . $val;
                })
                ->withAttr('param', function ($val1, $data) {
                    return json_decode($val1);
                })
                ->select();
            $count = $model->where($where)->count();
            $maxpage = ceil($count / $listRows);
            return sucessMsg('200', '获取成功', ['list' => $list, 'page' => $page, 'maxpage' => $maxpage]);
        }
    }

    /**
     * 获取实例详情
     */
    public function content()
    {
        $id = input('id/d');
        if (empty($id)) {
            return errMsg('500', '暂无数据');
        }
        $content = ExampleModel::where(['status' => 1, 'id' => $id])
            ->find();
        if (!empty($content['image'])) {
            $content['image'] = env('app.yuming') . $content['image'];
        }
        $content['param'] = json_decode($content['param']);
        $content['qian_path'] = env('app.yuming') . $content['qian_path'];
        $content['hou_path'] = env('app.yuming') . $content['hou_path'];
        //判断是否点赞
        $is_zan = ExampleZan::where(['status' => 1, 'example_id' => $id, 'zan_member_id' => $this->user_id])->count();
        $content['is_zan'] = 0;
        if ($is_zan > 0) $content['is_zan'] = 1;
        //判断是否收藏
        $is_col = ExampleCol::where(['status' => 1, 'example_id' => $id, 'col_member_id' => $this->user_id])->count();
        $content['is_col'] = 0;
        if ($is_col > 0) $content['is_col'] = 1;
        return sucessMsg('200', '获取成功', $content);
    }

    public function zan()
    {
        $example_id = input('id/d', 1);
        $is_zan = input('is_zan/d', 0);
        $model = New ExampleModel();
        $example_zanModel = New ExampleZan();
        $data = [];
        $data['zan_member_id'] = $this->user_id;
        $data['member_id'] = $model->where(['status' => 1, 'id' => $example_id])
            ->value('member_id');
        $data['example_id'] = $example_id;
        if ($is_zan == 0) {
            //开启事务
            Db::startTrans();
            try {
                $data['is_zan'] = 1;
                $example_zanModel->save($data);
                $model->where('id', $example_id)
                    ->inc('zan_num', 1)
                    ->update();
                Db::commit();
                return sucessMsg('200', '点赞成功');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return errMsg('400', '系统繁忙，请稍后再试');
            }
        } else {
            //开启事务
            Db::startTrans();
            try {
                $example_zanModel->where(['zan_member_id' => $data['zan_member_id'],
                    'member_id' => $data['member_id'],
                    'example_id' => $data['example_id']
                ])->delete();
                $model->where('id', $example_id)
                    ->dec('zan_num', 1)
                    ->update();
                Db::commit();
                return sucessMsg('200', '取消点赞成功');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return errMsg('400', '系统繁忙，请稍后再试');
            }
        }
    }

    public function col()
    {
        $example_id = input('id/d', 1);
        $is_col = input('is_col/d', 0);
        $model = New ExampleModel();
        $example_colModel = New ExampleCol();
        $data = [];
        $data['col_member_id'] = $this->user_id;
        $data['member_id'] = $model->where(['status' => 1, 'id' => $example_id])
            ->value('member_id');
        $data['example_id'] = $example_id;
        if ($is_col == 0) {
            //开启事务
            Db::startTrans();
            try {
                $data['is_col'] = 1;
                $example_colModel->save($data);
                $model->where('id', $example_id)
                    ->inc('col_num', 1)
                    ->update();
                Db::commit();
                return sucessMsg('200', '收藏成功');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return errMsg('400', '系统繁忙，请稍后再试');
            }
        } else {
            //开启事务
            Db::startTrans();
            try {
                $example_colModel->where(['col_member_id' => $data['col_member_id'],
                    'member_id' => $data['member_id'],
                    'example_id' => $data['example_id']
                ])->delete();
                $model->where('id', $example_id)
                    ->dec('col_num', 1)
                    ->update();
                Db::commit();
                return sucessMsg('200', '取消收藏成功');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return errMsg('400', '系统繁忙，请稍后再试');
            }
        }
    }

}
